<template>
  <div class="notification-settings">
    <t-form :data="formData" :label-width="120" @submit="handleSubmit">
      <!-- 邮件通知设置 -->
      <t-divider>邮件通知设置</t-divider>
      
      <t-form-item label="启用邮件通知">
        <t-switch v-model="formData.emailEnabled" />
      </t-form-item>
      
      <template v-if="formData.emailEnabled">
        <t-form-item label="SMTP服务器" name="smtpHost">
          <t-input v-model="formData.smtpHost" placeholder="请输入SMTP服务器地址" />
        </t-form-item>
        
        <t-form-item label="SMTP端口" name="smtpPort">
          <t-input-number v-model="formData.smtpPort" :min="1" :max="65535" />
        </t-form-item>
        
        <t-form-item label="加密方式" name="smtpEncryption">
          <t-radio-group v-model="formData.smtpEncryption">
            <t-radio-button value="none">无</t-radio-button>
            <t-radio-button value="ssl">SSL</t-radio-button>
            <t-radio-button value="tls">TLS</t-radio-button>
          </t-radio-group>
        </t-form-item>
        
        <t-form-item label="发件人邮箱" name="smtpEmail">
          <t-input v-model="formData.smtpEmail" placeholder="请输入发件人邮箱" />
        </t-form-item>
        
        <t-form-item label="发件人名称" name="smtpName">
          <t-input v-model="formData.smtpName" placeholder="请输入发件人名称" />
        </t-form-item>
        
        <t-form-item label="邮箱用户名" name="smtpUsername">
          <t-input v-model="formData.smtpUsername" placeholder="请输入邮箱用户名" />
        </t-form-item>
        
        <t-form-item label="邮箱密码" name="smtpPassword">
          <t-input
            v-model="formData.smtpPassword"
            type="password"
            placeholder="请输入邮箱密码"
            :password-visible="passwordVisible.email"
            @password-visible-change="(val: boolean) => passwordVisible.email = val"
          />
        </t-form-item>
        
        <t-form-item label="测试邮件">
          <t-input v-model="testEmail" placeholder="请输入测试邮箱地址" />
          <t-button theme="default" variant="base" @click="sendTestEmail" :loading="testEmailLoading">
            发送测试邮件
          </t-button>
        </t-form-item>
      </template>
      
      <!-- 短信通知设置 -->
      <t-divider>短信通知设置</t-divider>
      
      <t-form-item label="启用短信通知">
        <t-switch v-model="formData.smsEnabled" />
      </t-form-item>
      
      <template v-if="formData.smsEnabled">
        <t-form-item label="短信服务商" name="smsProvider">
          <t-select v-model="formData.smsProvider">
            <t-option key="aliyun" value="aliyun" label="阿里云" />
            <t-option key="tencent" value="tencent" label="腾讯云" />
            <t-option key="netease" value="netease" label="网易云信" />
          </t-select>
        </t-form-item>
        
        <template v-if="formData.smsProvider === 'aliyun'">
          <t-form-item label="AccessKey ID" name="aliyunAccessKeyId">
            <t-input v-model="formData.aliyunAccessKeyId" placeholder="请输入阿里云AccessKey ID" />
          </t-form-item>
          
          <t-form-item label="AccessKey Secret" name="aliyunAccessKeySecret">
            <t-input
              v-model="formData.aliyunAccessKeySecret"
              type="password"
              placeholder="请输入阿里云AccessKey Secret"
              :password-visible="passwordVisible.aliyun"
              @password-visible-change="(val: boolean) => passwordVisible.aliyun = val"
            />
          </t-form-item>
          
          <t-form-item label="短信签名" name="aliyunSignName">
            <t-input v-model="formData.aliyunSignName" placeholder="请输入短信签名" />
          </t-form-item>
        </template>
        
        <template v-if="formData.smsProvider === 'tencent'">
          <t-form-item label="SecretId" name="tencentSecretId">
            <t-input v-model="formData.tencentSecretId" placeholder="请输入腾讯云SecretId" />
          </t-form-item>
          
          <t-form-item label="SecretKey" name="tencentSecretKey">
            <t-input
              v-model="formData.tencentSecretKey"
              type="password"
              placeholder="请输入腾讯云SecretKey"
              :password-visible="passwordVisible.tencent"
              @password-visible-change="(val: boolean) => passwordVisible.tencent = val"
            />
          </t-form-item>
          
          <t-form-item label="短信应用ID" name="tencentSdkAppId">
            <t-input v-model="formData.tencentSdkAppId" placeholder="请输入短信应用ID" />
          </t-form-item>
          
          <t-form-item label="短信签名" name="tencentSignName">
            <t-input v-model="formData.tencentSignName" placeholder="请输入短信签名" />
          </t-form-item>
        </template>
        
        <t-form-item label="测试短信">
          <t-input v-model="testPhone" placeholder="请输入测试手机号码" />
          <t-button theme="default" variant="base" @click="sendTestSms" :loading="testSmsLoading">
            发送测试短信
          </t-button>
        </t-form-item>
      </template>
      
      <!-- 通知模板设置 -->
      <t-divider>通知模板设置</t-divider>
      
      <t-form-item label="通知事件">
        <t-select v-model="selectedTemplate" style="width: 200px;">
          <t-option v-for="template in templates" :key="template.id" :value="template.id" :label="template.name" />
        </t-select>
      </t-form-item>
      
      <template v-if="selectedTemplate">
        <t-form-item label="启用邮件">
          <t-switch v-model="currentTemplate.emailEnabled" />
        </t-form-item>
        
        <t-form-item v-if="currentTemplate.emailEnabled" label="邮件主题">
          <t-input v-model="currentTemplate.emailSubject" placeholder="请输入邮件主题" />
        </t-form-item>
        
        <t-form-item v-if="currentTemplate.emailEnabled" label="邮件内容">
          <t-textarea
            v-model="currentTemplate.emailContent"
            :autosize="{ minRows: 5, maxRows: 10 }"
            placeholder="请输入邮件内容，可使用变量：{username}, {orderId}, {amount}等"
          />
        </t-form-item>
        
        <t-form-item label="启用短信">
          <t-switch v-model="currentTemplate.smsEnabled" />
        </t-form-item>
        
        <t-form-item v-if="currentTemplate.smsEnabled" label="短信内容">
          <t-textarea
            v-model="currentTemplate.smsContent"
            :autosize="{ minRows: 3, maxRows: 6 }"
            placeholder="请输入短信内容，可使用变量：{username}, {orderId}, {amount}等"
          />
          <div class="form-item-help">短信内容应简洁明了，避免使用特殊符号和链接</div>
        </t-form-item>
        
        <t-form-item v-if="currentTemplate.smsEnabled" label="短信模板ID">
          <t-input v-model="currentTemplate.smsTemplateId" placeholder="请输入短信服务商提供的模板ID" />
        </t-form-item>
      </template>
      
      <t-form-item>
        <t-space>
          <t-button theme="primary" type="submit" :loading="submitLoading">保存设置</t-button>
          <t-button theme="default" variant="base" @click="resetForm">重置</t-button>
        </t-space>
      </t-form-item>
    </t-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'

// 测试邮箱和手机号
const testEmail = ref('')
const testPhone = ref('')
const testEmailLoading = ref(false)
const testSmsLoading = ref(false)

// 密码可见状态
const passwordVisible = reactive({
  email: false,
  aliyun: false,
  tencent: false
})

// 表单数据
const formData = reactive({
  // 邮件设置
  emailEnabled: false,
  smtpHost: '',
  smtpPort: 465,
  smtpEncryption: 'ssl',
  smtpEmail: '',
  smtpName: '',
  smtpUsername: '',
  smtpPassword: '',
  
  // 短信设置
  smsEnabled: false,
  smsProvider: 'aliyun',
  
  // 阿里云短信
  aliyunAccessKeyId: '',
  aliyunAccessKeySecret: '',
  aliyunSignName: '',
  
  // 腾讯云短信
  tencentSecretId: '',
  tencentSecretKey: '',
  tencentSdkAppId: '',
  tencentSignName: ''
})

// 通知模板
interface Template {
  id: string;
  name: string;
  emailEnabled: boolean;
  emailSubject: string;
  emailContent: string;
  smsEnabled: boolean;
  smsContent: string;
  smsTemplateId: string;
}

const templates = reactive<Template[]>([
  {
    id: 'register',
    name: '用户注册',
    emailEnabled: true,
    emailSubject: '欢迎注册贵州四季康养',
    emailContent: '尊敬的{username}，感谢您注册贵州四季康养平台。您的账号已创建成功，祝您使用愉快！',
    smsEnabled: true,
    smsContent: '【贵州四季康养】尊敬的{username}，感谢您注册贵州四季康养平台。您的账号已创建成功，祝您使用愉快！',
    smsTemplateId: 'SMS_123456789'
  },
  {
    id: 'order_created',
    name: '订单创建',
    emailEnabled: true,
    emailSubject: '您的订单已创建',
    emailContent: '尊敬的{username}，您的订单{orderId}已成功创建，金额为{amount}元。请在30分钟内完成支付，谢谢！',
    smsEnabled: true,
    smsContent: '【贵州四季康养】尊敬的{username}，您的订单{orderId}已创建，金额{amount}元，请在30分钟内完成支付。',
    smsTemplateId: 'SMS_123456790'
  },
  {
    id: 'payment_success',
    name: '支付成功',
    emailEnabled: true,
    emailSubject: '支付成功通知',
    emailContent: '尊敬的{username}，您的订单{orderId}已支付成功，感谢您的惠顾！',
    smsEnabled: true,
    smsContent: '【贵州四季康养】尊敬的{username}，您的订单{orderId}已支付成功，感谢您的惠顾！',
    smsTemplateId: 'SMS_123456791'
  }
])

const selectedTemplate = ref<string>('register')

// 当前选中的模板
const currentTemplate = computed(() => {
  return templates.find(t => t.id === selectedTemplate.value) || templates[0]
})

// 提交状态
const submitLoading = ref(false)

// 获取通知设置
const fetchSettings = async () => {
  try {
    // 这里应该从API获取数据
    // const { data } = await getNotificationSettings()
    
    // 模拟数据
    const data = {
      emailEnabled: true,
      smtpHost: 'smtp.example.com',
      smtpPort: 465,
      smtpEncryption: 'ssl',
      smtpEmail: 'noreply@example.com',
      smtpName: '贵州四季康养',
      smtpUsername: 'noreply@example.com',
      smtpPassword: '******',
      
      smsEnabled: true,
      smsProvider: 'aliyun',
      aliyunAccessKeyId: '******',
      aliyunAccessKeySecret: '******',
      aliyunSignName: '贵州四季康养'
    }
    
    // 填充表单数据
    if (data) {
      Object.assign(formData, data)
    }
    
    // 模拟获取模板数据
    // const templateData = await getNotificationTemplates()
    // if (templateData) {
    //   Object.assign(templates, templateData)
    // }
  } catch (error) {
    console.error('获取通知设置失败', error)
    MessagePlugin.error('获取通知设置失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  submitLoading.value = true
  try {
    // 这里应该调用API保存数据
    // await updateNotificationSettings(formData)
    // await updateNotificationTemplates(templates)
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    MessagePlugin.success('保存成功')
  } catch (error) {
    console.error('保存通知设置失败', error)
    MessagePlugin.error('保存通知设置失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  fetchSettings()
}

// 发送测试邮件
const sendTestEmail = async () => {
  if (!testEmail.value) {
    MessagePlugin.warning('请输入测试邮箱地址')
    return
  }
  
  testEmailLoading.value = true
  try {
    // 这里应该调用API发送测试邮件
    // await sendTestEmailApi({
    //   email: testEmail.value,
    //   ...formData
    // })
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    MessagePlugin.success('测试邮件发送成功')
  } catch (error) {
    console.error('发送测试邮件失败', error)
    MessagePlugin.error('发送测试邮件失败')
  } finally {
    testEmailLoading.value = false
  }
}

// 发送测试短信
const sendTestSms = async () => {
  if (!testPhone.value) {
    MessagePlugin.warning('请输入测试手机号码')
    return
  }
  
  testSmsLoading.value = true
  try {
    // 这里应该调用API发送测试短信
    // await sendTestSmsApi({
    //   phone: testPhone.value,
    //   ...formData
    // })
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    MessagePlugin.success('测试短信发送成功')
  } catch (error) {
    console.error('发送测试短信失败', error)
    MessagePlugin.error('发送测试短信失败')
  } finally {
    testSmsLoading.value = false
  }
}

// 初始化
onMounted(() => {
  fetchSettings()
})
</script>

<style scoped>
.notification-settings {
  padding: 20px 0;
}

.form-item-help {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.4);
  margin-top: 4px;
}
</style> 